import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'

import qs from 'qs'

// 创建axios实例
const service = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '/api/' : `${process.env.VUE_APP_URL}`,
    transformRequest: [function (data) {
        return qs.stringify({
            ...data
        })
    }]
})

// request拦截器
service.interceptors.request.use(
    config => {

        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        if (store.getters.token) {
            config.headers.Authorization = `${store.getters.token}`
        }

        return config
    },
    error => {
        // Do something with request error

        Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(
    response => {
        /**
         * code为非20000是抛错 可结合自己业务进行修改
         */


        return response.data
    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
